import {promptBox, base, toast} from 'nc-lightapp-front';

export default class MainAction {

    constructor(comp) {
        this.comp = comp;
    }

    editListAction = (record) => {
        const {dispatch, myLeave, form} = this.comp.props;
        let formCode = myLeave.activeTab + '_card'
        const {setFormStatus, setAllFormValue, EmptyAllFormValue, getFormItemsValue} = form
        EmptyAllFormValue(formCode)
        dispatch({
            type: 'myLeave/update',
            payload: {
                showMode: 'card',
                isEdit: true,
                approvestatus: record.values['approvestatus'] && record.values['approvestatus'].value
            }
        })
        setFormStatus(formCode, 'edit')
        setAllFormValue({
            [formCode]: {
                rows: [record]
            }
        })
    }

    updateStateCustom = (state) => {
        this.comp.props.dispatch({
            type: 'myLeave/update',
            state
        });
    }

    getClientHeight = () => {
        let {width} = document.querySelector('#app').getBoundingClientRect()
        let height = document.documentElement.clientHeight - 200;
        width = width - 256;
        this.comp.props.dispatch({
            type: 'myLeave/update',
            payload: {
                clientHeight: height,
                clientWidth: width
            }
        })
    }

    getTempalte = () => {
        const {dispatch} = this.comp.props;
        dispatch({
            type: 'myLeave/languageCreateUIDOM',
            payload: {
                ...this.comp.props,
                callback: this.initailMeta
            }
        })
    }

    getLangCode = (sName) => {
        var sRE = "(?:; )?" + sName + "=([^;]*);?";
        var oRE = new RegExp(sRE);
        if (oRE.test(document.cookie)) {
            return RegExp["$1"];
        }
        return null;
    }

    addOperateCol = (template, buttons) => {
        const {myLeave, button} = this.comp.props;
        let langCode = this.getLangCode('langCode');
        let oprWidth = '160px', oproffWidth = '160px'
        if (langCode === 'english') {
            oprWidth = '250px'
            oproffWidth = '250px'
        }
        let render = (text, record, index) => {
            let edit = record.values.billtype.value === '6QCC'
                && record.values.approvestatus
                && record.values.approvestatus.value === '-1'
            let recall = record.values.approvestatus
                && (record.values.approvestatus.value - 0) === 3
            let revoke = record.values.billtype.value === '6QCC'
                && record.values.approvestatus
                && record.values.approvestatus.value === '1'
                && (record.values.billsource.value
                    && record.values.billsource.value === '0')
                && (record.values.tripoffapprovestatus
                    && !record.values.tripoffapprovestatus.value)

            let listBtns = []
            buttons.forEach(btn => {
                if (btn.area === 'list') {
                    if ((btn.key === 'list_submit' || btn.key === 'list_edit'
                        || btn.key === 'list_del') && !edit) {
                        return
                    }
                    if (btn.key === 'list_withdraw' && !recall) {
                        return
                    }
                    if (btn.key === 'list_revoke' && !revoke) {
                        return
                    }
                    listBtns.push(btn.key)
                }
            })

            return (
                <div className="currency-opr-col">
                    {button.createOprationButton(listBtns,
                        {
                            area: 'list',
                            buttonLimit: 2,
                            onButtonClick: (props, id, e) => {
                                this.listClickHandle(id, record)
                            }
                        }
                    )}
                </div>
            );
        }
        let renderoff = (text, record, index) => {
            let edit = record.values.tripoffapprovestatus
                && record.values.tripoffapprovestatus.value === '-1'
            let recall = record.values.tripoffapprovestatus
                && record.values.tripoffapprovestatus.value === '3'
            let look = record.values.approvestatus.value === '1'
                && (record.values.tripoffapprovestatus
                    && record.values.tripoffapprovestatus.value)
            let offBtns = []
            if (record.values.tripoffapprovestatus && record.values.tripoffapprovestatus.value) {
                buttons.forEach(btn => {
                    if (btn.area === 'list_off') {
                        if ((btn.key === 'off_submit' || btn.key === 'off_edit'
                            || btn.key === 'off_del') && !edit) {
                            return
                        }
                        if (btn.key === 'off_withdraw' && !recall) {
                            return
                        }
                        offBtns.push(btn.key)
                    }
                })
            }

            return (
                <div className="currency-opr-col">
                    {button.createOprationButton(offBtns,
                        {
                            area: 'list_off',
                            buttonLimit: 2,
                            onButtonClick: (props, id, e) => {
                                this.listOffClickHandle(id, record)
                            }
                        }
                    )}
                </div>
            );
        }

        template['trip_list'].items.push({
            attrcode: 'operation',
            renderStatus: 'browse',
            itemtype: 'customer',
            label: myLeave.json['6040-000019'], /* 国际化处理： 操作*/
            width: oprWidth,
            visible: true,
            fixed: 'right',
            render: render
        })

        template['trip_list'].items.push({
            attrcode: 'oproff',
            renderStatus: 'browse',
            itemtype: 'customer',
            label: myLeave.json['6040-000028'], /* 国际化处理： 操作*/
            width: oproffWidth,
            visible: true,
            fixed: 'right',
            render: renderoff
        })
    }

    listClickHandle = (key, record) => {
        if (key === 'list_flow') {
            this.showFlowHistory(record, 1)
        } else if (key === 'list_withdraw') {
            this.recallBill(record)
        } else if (key === 'list_revoke') {
            this.linkBill(record)
        } else if (key === 'list_submit') {
            this.submitBill(record, 'trip')
        } else if (key === 'list_file') {
            this.showUploader(record);
        } else if (key === 'list_edit') {
            this.editBill(record);
        } else if (key === 'list_del') {
            this.deleteBill(record, 'trip');
        }
    }

    listOffClickHandle = (key, record) => {
        if (key === 'off_flow') {
            this.showFlowHistory(record, 2)
        } else if (key === 'off_withdraw') {
            this.recallBill(record)
        } else if (key === 'off_check') {
            this.onLookClick(record, 'browse')
        } else if (key === 'off_submit') {
            this.submitBill(record, 'tripoff')
        } else if (key === 'off_edit') {
            this.onLookClick(record, 'edit');
        } else if (key === 'off_del') {
            this.deleteBill(record, 'tripoff');
        }
    }

    initailMeta = (metas, lang, intl) => {
        let {button, template} = metas;
        const props = this.comp.props;
        const {renderItem, meta, dispatch} = props;
        dispatch({
            type: 'myLeave/update',
            payload: {
                json: lang
            }
        })
        this.addOperateCol(template, button);
        this.handleMeta(template, renderItem)
        meta.setMeta(template ? template : {});
        props.button.setButtons(button);
        dispatch({
            type: 'myLeave/update',
            payload: {
                templateInited: true
            }
        })
    }

    handleMeta = (template, renderItem) => {
        const {myLeave} = this.comp.props;
        let target = ['trip_card', 'tripoff_card', 'trip_list'];
        target.forEach(key => {
            template[key].items.forEach(item => {
                if (key === 'trip_card') {
                    if (item.attrcode === 'tripday') {
                        item.itemtype = 'input'
                    }
                    if (item.attrcode === 'transtypeid') {
                        if (!item.queryCondition) {
                            item.queryCondition = {
                                GridRefActionExt: "nccloud.web.hrkq.trip.sqlbuilder.TripTransTypeRefSqlBuilder"
                            }
                        } else {
                            item.queryCondition = Object.assign(item.queryCondition, {
                                GridRefActionExt: "nccloud.web.hrkq.trip.sqlbuilder.TripTransTypeRefSqlBuilder"
                            })
                        }
                    } else if (item.attrcode === "pk_attend_staff") {
                        if (!item.queryCondition) {
                            item.queryCondition = {}
                        }
                        item.queryCondition = Object.assign(item.queryCondition, {
                            isSingle: "1"
                        })
                    }
                }
                if (key === 'tripoff_card') {
                    if (item.attrcode === 'tripoffday' || item.attrcode === 'tripday') {
                        item.itemtype = 'input'
                    }
                    if (item.attrcode === 'transtypeid') {
                        if (!item.queryCondition) {
                            item.queryCondition = {
                                GridRefActionExt: "nccloud.web.hrkq.tripoff.sqlbuilder.TripOffTransTypeRefSqlBuilder"
                            }
                        } else {
                            item.queryCondition = Object.assign(item.queryCondition, {
                                GridRefActionExt: "nccloud.web.hrkq.tripoff.sqlbuilder.TripOffTransTypeRefSqlBuilder"
                            })
                        }
                    }
                }
                if (key === 'trip_list') {
                    if (item.attrcode === 'tripday') {
                        item.itemtype = 'input';
                        item.renderStatus = 'browse';
                        item.render = (text, record, index) => {
                            return (
                                <span>
                                    {(record.values && record.values['tripday'].value) + (record.values && record.values['minunit'].display)}
                                </span>
                            );
                        };
                    }
                    if (item.attrcode === 'tripbegintime' || item.attrcode === 'tripendtime') {
                        item.renderStatus = 'browse';
                        item.render = (text, record, index) => {
                            return (
                                <span style={{textAlign: 'right'}}>
                                    {record.values && record.values[item.attrcode].value.slice(0, -3)}
                                </span>
                            );
                        };
                    }
                }
            })
        })
    }
    /**
     * @desc: 根据休假类型的单位和最小请假时间 格式化请假时间
     * @param {type}
     * @return: 最终要显示的日期
     */
    formatDisplayDate = (record, attrcode) => {
        if (!record || !record.values || !record.values[attrcode].value) {
            return '';
        }
        let isHour = record.values['minunit'].value === '1';
        let isHalfDate = !!record.values['start_day_type'].value;
        let values = record.values;
        if (values.breastfeedingleaveday && values.breastfeedingleaveday.value && values.breastfeedingleaveway && values.breastfeedingleaveway.value) {
            // 如果是哺乳假 则 返回 日期 不返回小时 分钟
            return record.values[attrcode].value.slice(0, -8);
        }

        if (isHour) {
            return record.values[attrcode].value.slice(0, -3);
        } else {
            attrcode = attrcode === 'begintime' ? 'showbegindate' : 'showenddate';
            if (isHalfDate) {
                return record.values[attrcode].value.replace(/\s([\d\:]+)/, (a, b) => {
                    return attrcode === 'showbegindate' ? record.values['start_day_type'].display : record.values['end_day_type'].display;
                })
            } else {
                return record.values[attrcode].value.slice(0, -8);
            }
        }
    }
    /**
     * @desc:
     * @param {type}
     * @return:
     */
    showFlowHistory = (record, type) => {
        const {dispatch, myLeave} = this.comp.props;
        let billId
        let billtype
        if (type === 1) {
            billtype = (record.values['transtype'] && record.values['transtype'].value) || '6QCC'
            billId = record.values['pk_trip'].value;
        } else if (type === 2) {
            billtype = (record.values['tripofftranstype'] && record.values['tripofftranstype'].value) || "6QXC"
            billId = record.values['pk_tripoff'].value;
        }

        dispatch({
            type: 'myLeave/update',
            payload: {
                showApproveDetail: true,
                billId,
                billtype
            }
        })
    }
    /**
     * @desc: 跳转销差销假操作
     * @param {type}
     * @return:
     *
     */
    linkBill = (record) => {
        const formCode = 'tripoff_card'
        const activeTab = 'tripoff'
        const {dispatch, myLeave, form, renderItem} = this.comp.props
        const {
            setFormStatus,
            setAllFormValue,
            EmptyAllFormValue,
            getFormItemsValue,
            setItemsVisible,
            setFormItemsDisabled,
            setFormItemsRequired
        } = form
        EmptyAllFormValue(formCode)
        dispatch({
            type: 'myLeave/AddAction',
            payload: {
                key: activeTab,
                operat: 0,
                pk_other: record.values.pk_trip.value
            }
        }).then(res => {
            this.setRecokeValue(this.comp.props, res.data[formCode], record, 'add')
        })
    }

    submitBill = (record, key) => {
        const {dispatch, myLeave} = this.comp.props;
        dispatch({
            type: 'myLeave/submitBillAction',
            payload: {
                key,
                pk: record.values['pk_' + key].value
            }
        }).then(res => {
            if (res.success) {
                if (res.data && res.data.content) {
                    dispatch({
                        type: 'myLeave/update',
                        payload: {
                            assignedData: res.data.content,
                            assignedDisplay: true
                        }
                    })
                } else {
                    toast({
                        color: 'success',
                        content: myLeave.json['6040-00004']  // 提交成功！
                    });
                    this.queryListAction()
                }
            }
        })
    }

    showUploader = (record) => {
        const {dispatch} = this.comp.props;
        dispatch({
            type: 'myLeave/update',
            payload: {
                showUploader: true,
                billId: record.values['pk_trip'].value,
                approvestatus: record.values['approvestatus'].value,
            }
        })
    }

    editBill = (record) => {
        const {dispatch, myLeave, form} = this.comp.props;
        let minTime = '';
        let formCode = myLeave.activeTab + '_card';
        const {
            setFormStatus, setAllFormValue,
            EmptyAllFormValue, setFormItemsValue
        } = form;
        EmptyAllFormValue(formCode);
        setFormStatus(formCode, 'edit');
        setAllFormValue({
            [formCode]: {
                rows: [record]
            }
        })
        if (formCode === 'trip_card') {
            let dayKey = 'tripday';
            setFormItemsValue(formCode, {
                [dayKey]: {
                    display: record.values[dayKey].value + record.values['minunit'].display,
                    value: record.values[dayKey].value
                }
            });
            let cardDefaultDisabled = {
                tripbegintime: false, // 开始日期
                tripendtime: false // 结束日期
            }
            form.setFormItemsDisabled(formCode, cardDefaultDisabled);
            this.setTypeCondition(formCode, record)
        }

        dispatch({
            type: 'myLeave/update',
            payload: {
                showMode: 'card',
                isEdit: true,
                minTime,
                billId: record.values['pk_' + myLeave.activeTab].value,
                headerTitle: myLeave.subTitle,
                approvestatus: record.values['approvestatus'] && record.values['approvestatus'].value
            }
        })
    }

    deleteBill = (record, key) => {
        const {dispatch, myLeave} = this.comp.props
        promptBox({
            color: "warning",
            title: myLeave.json['6040-00005'], /* 国际化处理： 提示*/
            content: myLeave.json['6040-000060'],
            beSureBtnClick: () => {
                dispatch({
                    type: 'myLeave/deleteAction',
                    payload: {
                        activeTab: key,
                        pk: record.values['pk_' + key].value
                    }
                }).then(res => {
                    if (res.success) {
                        toast({
                            color: 'success',
                            content: myLeave.json['6040-000012']
                        })
                        this.queryListAction();
                    }
                })
            }
        })
    }

    setTypeCondition = (formCode, record) => {
        const {meta} = this.comp.props;
        let temp = meta.getMeta();
        let pk_attend_staff = record.values.pk_attend_staff && record.values.pk_attend_staff.value
        temp[formCode].items.forEach(item => {
            if (item.attrcode === "triptypeid") {
                item.queryCondition = function () {
                    return {
                        pk_attend_staff: pk_attend_staff
                    }
                }
            }
        });
        meta.setMeta(temp);
    }

    setRecokeValue(props, template, record, status) {
        const {dispatch, form, myLeave, renderItem} = props
        const formCode = 'tripoff_card'
        const activeTab = 'tripoff'
        const titleName = myLeave.json['6040-000031']
        let minTime = '1'
        let feedStatus = false
        let cardDefaultVisiable = {}
        let cardDefaultDisabled = {}
        const {
            setFormStatus,
            setAllFormValue,
            EmptyAllFormValue,
            getFormItemsValue,
            setItemsVisible,
            setFormItemsDisabled,
            setFormItemsRequired
        } = form
        if (formCode === 'tripoff_card') {
            cardDefaultDisabled = {
                tripbegintime: true, // 开始日期
                tripendtime: true // 结束日期
            }
            let dr_flag = template.rows[0].values.dr_flag.value
            // 出差时间有变化 显示 开始、结束日期 和 销差天数
            cardDefaultVisiable.tripoffbegintime = dr_flag !== '1' // 开始日期
            cardDefaultVisiable.tripoffendtime = dr_flag !== '1' // 结束日期
            cardDefaultVisiable.tripoffday = dr_flag !== '1' // 结束时间

            template.rows[0].values.tripday.display = `${template.rows[0].values.tripday.value}${template.rows[0].values.minunit.value === "1" ? myLeave.json['6040-000014'] : myLeave.json['6040-000015']}`
            template.rows[0].values.tripoffday.display = template.rows[0].values.tripoffday.value ? `${template.rows[0].values.tripoffday.value}${template.rows[0].values.minunit.value === "1" ? myLeave.json['6040-000014'] : myLeave.json['6040-000015']}` : null
        }
        setItemsVisible(formCode, cardDefaultVisiable);
        dispatch({
            type: 'myLeave/update',
            payload: {
                feedStatus,
                showMode: 'card',
                isEdit: status === 'add',
                headerTitle: titleName
            }
        })
        setAllFormValue({[formCode]: template});
        let billId = getFormItemsValue(formCode, 'pk_' + activeTab).value;
        let approvestatus = getFormItemsValue(formCode, 'approvestatus').value;
        dispatch({
            type: 'myLeave/update',
            payload: {
                billId,
                minTime,
                activeTab: activeTab,
                approvestatus
            }
        })
        cardDefaultVisiable = null
        cardDefaultDisabled = null
        setFormStatus(formCode, status)
    }

    /**
     * @desc: record(行数据) ，index(当前index) props, e (事件对象)
     * @param {type}
     * @return:
     */
    onLookClick = (record, status = 'browse') => {
        const {dispatch, myLeave, form, renderItem, button} = this.comp.props
        let formCode = myLeave.activeTab + 'off' + '_card';
        const activeTab = 'tripoff'
        const {
            setFormStatus,
            setAllFormValue,
            EmptyAllFormValue,
            getFormItemsValue,
            setItemsVisible,
            setFormItemsDisabled,
            setFormItemsRequired
        } = form
        EmptyAllFormValue(formCode)
        dispatch({
            type: 'myLeave/queryByIdAction',
            payload: {
                key: activeTab,
                pk: record.values['pk_' + myLeave.activeTab].value
            }
        }).then(res => {
            this.setRecokeValue(this.comp.props, res.data[myLeave.activeTab + 'off'][formCode], record, status)
        })
    }
    /**
     * @desc: 单据撤回操作
     * @param {type}
     * @return:
     */
    recallBill = (record) => {
        const {dispatch, myLeave, editTable} = this.comp.props;
        let pk = record.values['pk_' + myLeave.activeTab].value;
        let tableCode = myLeave.activeTab + '_list';
        let activeTab = myLeave.activeTab
        let status = record.values.approvestatus.value;
        let revokestatus = record.values.approvestatus.value === '1' && (record.values.tripoffapprovestatus && record.values.tripoffapprovestatus.value || record.values.leaveoffapprovestatus && record.values.leaveoffapprovestatus.value)
        if (status === '1' && revokestatus === '3') {
            pk = record.values['pk_' + myLeave.activeTab + 'off'].value;
            activeTab = myLeave.activeTab + 'off'
        }
        promptBox({
            color: "warning",
            title: myLeave.json['6040-00005'], /* 国际化处理： 提示*/
            content: myLeave.json['6040-000023'], /* 国际化处理： 你确定要撤回该单据吗？*/
            beSureBtnClick: () => {
                dispatch({
                    type: 'myLeave/recallAction',
                    payload: {
                        key: activeTab,
                        pk
                    }
                }).then(res => {
                    if (res.success) {
                        toast({
                            color: 'success',
                            content: myLeave.json['6040-000024']
                        });
                        dispatch({
                            type: 'myLeave/queryListAction',
                            payload: {
                                key: myLeave.activeTab,
                                beginDate: myLeave.beginValue,
                                endDate: myLeave.endValue
                            }
                        }).then(res => {
                            if (res.success) {
                                if (res.data) {
                                    editTable.setTableData(tableCode, res.data[tableCode])
                                    dispatch({
                                        type: 'myLeave/update',
                                        payload: {
                                            [myLeave.activeTab + 'PageInfo']: res.data[tableCode].pageInfo
                                        }
                                    })
                                }
                            }
                        })
                    }
                })
            }
        })
    }
    closeApproveDetailDialog = () => {
        const {dispatch} = this.comp.props;
        dispatch({
            type: 'myLeave/update',
            payload: {
                showApproveDetail: false
            }
        })
    }
    handlePageIndexChange = (pageIndex) => {
        const {dispatch, myLeave} = this.comp.props
        let pageInfo = myLeave.activeTab + 'PageInfo'
        dispatch({
            type: 'myLeave/update',
            payload: {
                [pageInfo]: Object.assign({}, myLeave[pageInfo], {
                    pageIndex
                })
            }
        })
        this.queryListAction()
    }

    queryListAction = () => {
        const {dispatch, myLeave, editTable} = this.comp.props;
        let tableCode = myLeave.activeTab + '_list';
        let activeTab = myLeave.activeTab
        dispatch({
            type: 'myLeave/queryListAction',
            payload: {
                key: myLeave.activeTab,
                beginDate: myLeave.beginValue,
                endDate: myLeave.endValue
            }
        }).then(res => {
            if (res.success) {
                if (res.data) {
                    editTable.setTableData(tableCode, res.data[tableCode])
                    dispatch({
                        type: 'myLeave/update',
                        payload: {
                            [activeTab + 'PageInfo']: res.data[tableCode].pageInfo
                        }
                    })
                } else {
                    editTable.setTableData(tableCode, {rows: []})
                    dispatch({
                        type: 'myLeave/update',
                        payload: {
                            [activeTab + 'PageInfo']: Object.assign({}, myLeave[activeTab + 'PageInfo'], {total: null})
                        }
                    })
                }
            }
        })
    }

    didMount = () => {
        if (window.location.href.match(/(localhost|127\.0\.0\.1)/)) {
            window.location.hash = `#ifr?page=2019916105952100`;
        }
        this.getClientHeight()
        this.getTempalte()
    }
}